#!/usr/bin/env bash

# Filename     :	docker-install.sh
# Last modified:	2024-08-30 12:12
# Version      : 1.1.0
# Author       : jack.zang
# Email        : jack.zang@aishangwei.net
# Description  : Docker自动安装脚本，支持Ubuntu和CentOS系统
# 使用方法：(source <(curl -sL https://gitee.com/jack_zang/public-scripts/raw/master/shell/docker/docker-install.sh))
# ******************************************************

set -e

# 设置日志颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [ "$(id -u)" != "0" ]; then
        log_error "此脚本需要root权限运行"
        exit 1
    fi
}

# 检查必要的系统工具
check_system_tools() {
    local tools=("curl" "wget" "gpg")
    for tool in "${tools[@]}"; do
        if ! command -v "$tool" &> /dev/null; then
            log_warn "正在安装必要的系统工具: $tool"
            if [ "$OS" = "ubuntu" ]; then
                apt-get install -y "$tool"
            elif [ "$OS" = "centos" ]; then
                yum install -y "$tool"
            fi
        fi
    done
}

install_docker_ubuntu() {
    log_info "开始安装Docker (Ubuntu)"
    
    # 安装必要的依赖包
    log_info "安装系统依赖"
    apt-get update
    apt-get install -y apt-transport-https ca-certificates curl software-properties-common

    # 添加Docker官方GPG密钥
    log_info "添加Docker GPG密钥"
    if ! curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-ce-keyrings.gpg; then
        log_error "添加Docker GPG密钥失败"
        return 1
    fi

    # 设置Docker软件源
    log_info "配置Docker软件源"
    echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-ce-keyrings.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
    #echo "deb https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
    # 更新软件包索引并安装Docker
    log_info "安装Docker引擎"
    apt-get update
    if ! apt-get install -y docker-ce docker-ce-cli containerd.io; then
        log_error "Docker安装失败"
        return 1
    fi

    # 创建docker配置目录
    mkdir -p /etc/docker

    # 配置Docker镜像加速和其他参数
    log_info "配置Docker运行参数"
    cat > /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": [
    "https://docker.1ms.run",
    "https://docker.mybacc.com",
    "https://dytt.online",
    "https://lispy.org",
    "https://docker.xiaogenban1993.com",
    "https://docker.yomansunter.com",
    "https://aicarbon.xyz",
    "https://666860.xyz",
    "https://docker.zhai.cm",
    "https://a.ussh.net",
    "https://hub.littlediary.cn",
    "https://hub.rat.dev",
    "https://docker.m.daocloud.io"
  ]
}
EOF
}

install_docker_centos() {
    log_info "开始安装Docker (CentOS)"

    # 安装必要的依赖包
    log_info "安装系统依赖"
    yum install -y yum-utils device-mapper-persistent-data lvm2

    # 添加Docker软件源
    log_info "配置Docker软件源"
    if ! yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo; then
        log_error "添加Docker软件源失败"
        return 1
    fi

    # 安装Docker
    log_info "安装Docker引擎"
    if ! yum install -y docker-ce docker-ce-cli containerd.io; then
        log_error "Docker安装失败"
        return 1
    fi

    # 创建docker配置目录
    mkdir -p /etc/docker

    # 配置Docker镜像加速和其他参数
    log_info "配置Docker运行参数"
    cat > /etc/docker/daemon.json <<EOF
{
  "registry-mirrors": [
    "https://docker.1ms.run",
    "https://docker.mybacc.com",
    "https://dytt.online",
    "https://lispy.org",
    "https://docker.xiaogenban1993.com",
    "https://docker.yomansunter.com",
    "https://aicarbon.xyz",
    "https://666860.xyz",
    "https://docker.zhai.cm",
    "https://a.ussh.net",
    "https://hub.littlediary.cn",
    "https://hub.rat.dev",
    "https://docker.m.daocloud.io"
  ],
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "10"
  },
  "storage-driver": "overlay2",
  "storage-opts":["overlay2.override_kernel_check=true"],
  "live-restore": true
}
EOF
}


# 配置Docker安全设置
configure_docker_security() {
    log_info "配置Docker安全设置"
    
    # 创建docker用户组
    groupadd docker 2>/dev/null || true
    
    # 将当前用户添加到docker组
    usermod -aG docker "${SUDO_USER:-$USER}" 2>/dev/null || true
    
    # 设置Docker服务目录权限
    chmod 700 /etc/docker
    chmod 600 /etc/docker/daemon.json
}

# 检查Docker是否已安装
check_docker_installed() {
  if command -v docker &> /dev/null; then
    log_info "Docker已经安装在系统中"
    docker --version
    return 2
  fi
}

# 主安装流程
main() {
    # 检查Docker是否已安装
    check_docker_installed
    if [ $? -eq 2 ]; then
        return 0
    fi
    
    # 检查root权限
    check_root
    
    # 检查操作系统类型
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$ID
    else
        log_error "无法确定操作系统类型"
        exit 1
    fi
    
    # 检查系统工具
    check_system_tools
    
    # 根据操作系统类型安装docker
    log_info "开始安装Docker"
    case $OS in
        ubuntu)
            install_docker_ubuntu
            ;;
        centos)
            install_docker_centos
            ;;
        *)
            log_error "不支持的操作系统类型：$OS"
            exit 1
            ;;
    esac
    
    # 启动Docker服务
    log_info "启动Docker服务"
    systemctl daemon-reload
    if ! systemctl start docker; then
        log_error "Docker服务启动失败"
        exit 1
    fi
    
    # 设置开机自启
    systemctl enable docker
    
    # 配置安全设置
    configure_docker_security
    
    # 验证安装
    log_info "验证Docker安装"
    docker --version
    
    log_info "Docker安装完成！"
    log_info "查看Docker信息以检查安装详情"
    docker info
}

# 执行主安装流程
main
